package timing.ukulele.gateway.filter;

import com.alibaba.fastjson.JSON;
import timing.ukulele.common.Constant;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.common.ResultCode;
import timing.ukulele.common.portal.SystemData;
import timing.ukulele.gateway.client.PortalClient;
import timing.ukulele.gateway.config.JwtProperties;
import timing.ukulele.gateway.utils.JWTUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    private final JwtProperties jwtProperties;

    private final PathMatcher pathMatcher;

    @Resource
    @Lazy
    private PortalClient portalClient;

    public TokenFilter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
        this.pathMatcher = new AntPathMatcher();
    }

    /**
     * 请求方式验证过滤器
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        if (this.pathMatcher.match("/**/provider/**", serverHttpRequest.getPath().toString())) {
            String token = serverHttpRequest.getHeaders().getFirst(Constant.BIZ_TOKEN);
            if (StringUtils.isBlank(token)) {
                serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
                return getVoidMono(serverHttpResponse, ResultCode.UNAUTHORIZED);
            }
            String appId = serverHttpRequest.getHeaders().getFirst(Constant.APP);
            if (StringUtils.isBlank(appId)) {
                serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
                return getVoidMono(serverHttpResponse, ResultCode.UNAUTHORIZED);
            }
            ResponseResult<SystemData> response = portalClient.getSystemById(appId);
            if (response == null || response.getData() == null || StringUtils.isEmpty(response.getData().getApplyUrl())) {
                serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
                return getVoidMono(serverHttpResponse, ResultCode.UNAUTHORIZED);
            }
            String encryptString = DigestUtils.md5Hex(appId + response.getData().getAppSecret());
            if (encryptString.equals(token.toLowerCase())) {
                ServerHttpRequest mutableReq = serverHttpRequest.mutate()
                    .header(Constant.SYSTEM, appId)
                    .build();
                ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
                return chain.filter(mutableExchange);
            } else {
                serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
                return getVoidMono(serverHttpResponse, ResultCode.UNAUTHORIZED);
            }
        } else {
            String token = serverHttpRequest.getHeaders().getFirst(Constant.TOKEN);
            if (StringUtils.isBlank(token)) {
                serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
                return getVoidMono(serverHttpResponse, ResultCode.UNAUTHORIZED);
            }
            Map<String, Object> stringObjectMap;
            try {
                stringObjectMap = JWTUtil.verifyJavaWebToken(token, jwtProperties.getSecretKey());
            } catch (Exception ex) {
                return getVoidMono(serverHttpResponse, ResultCode.UNAUTHORIZED);
            }
            if (stringObjectMap == null || stringObjectMap.get(Constant.USER_INFO) == null) {
                return getVoidMono(serverHttpResponse, ResultCode.UNAUTHORIZED);
            }
            LinkedHashMap<String, Object> userDetails = (LinkedHashMap) stringObjectMap.get(Constant.USER_INFO);
            List<String> systemIds = (List<String>) userDetails.get("systemIds");
            String system = null;
            if (!CollectionUtils.isEmpty(systemIds)) {
                system = String.join(",", systemIds);
            }
            ServerHttpRequest mutableReq = serverHttpRequest.mutate()
                    .header(Constant.USERNAME, (String) userDetails.get("username"))
                    .header(Constant.SYSTEM, system)
                    .header(Constant.ROLE, String.valueOf(userDetails.get("role")))
                    .build();
            ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
            return chain.filter(mutableExchange);
        }
    }

    private Mono<Void> getVoidMono(ServerHttpResponse serverHttpResponse, ResultCode responseCodeEnum) {
        serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ResponseResult<Void> responseResult = ResponseResult.error(responseCodeEnum.getMsg());
        DataBuffer dataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(responseResult).getBytes());
        return serverHttpResponse.writeWith(Flux.just(dataBuffer));
    }

    /**
     * 优先级*
     *
     * @return int 数字越大优先级越低
     */
    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }


}
